<script setup lang="ts">
  import { postLoginAPI, saveClDevice, checkDevice, getMiniprogramOpenId, getMpToken, getopenIds, getUsers, getOpenId } from '@/services/login'
  import { useMemberStore } from '@/stores'
  import type { LoginResult } from '@/types/member'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  import w_md5 from '../../js_sdk/zww-md5/w_md5.js'
  import Func from '@/utils/func'

  //自定义样式
  const styles = "{ color: '#333',backgroundColor: rgba(179, 220, 246, 0.10),disableColor: '#F7F6F6',borderColor: '#e5e5e5'}"
  const placeholderStyle = "{ color: '#333',font-size:32rpx}"
  const loading = ref(false)
  const deviceNumber = ref('')
  let deviceType = ''
  const memberStore = useMemberStore()
  const form = ref({
    loginName: '',
    passwd: '',
  })
  //用于展示关注公众号
  const visible = ref(false)

  onLoad(async () => {

    form.value.loginName = uni.getStorageSync('account') || ''
    form.value.passwd = uni.getStorageSync('password') || ''

    //获取设备号 清除缓存后会发生变化
    const systemInfo = uni.getSystemInfoSync()
    console.log(systemInfo)

    const key = `${systemInfo.brand}-${systemInfo.model}-${systemInfo.system}-${systemInfo.deviceType}`;
    const hash = w_md5.hex_md5_32(key); // 生成 MD5 32位哈希
    console.log('设备标识（MD5）：', hash);
    deviceNumber.value = hash
    deviceType = systemInfo.deviceModel
    // wxLogin()

  })

  //微信授权
  function wxLogin() {
    uni.showLoading({
      title: ''
    })
    uni.login({
      provider: 'weixin',
      success: async function (loginRes) {
        console.log(loginRes.code);
        let targetOpenId = ''

        // 获取小程序的 openid 和 unionid
        const miniProgram : any = await getMiniprogramOpenId(loginRes.code)
        //获取公众号的 token
        const mpTokenBean : any = await getMpToken()
        //获取公众号的 openid 列表
        const result : any = await getopenIds(mpTokenBean.access_token)
        if (result && result.data.openid) {
          const openIds = result.data.openid.map((id : string) => {
            return { openid: id }
          })
          //openidList 超过100 分片请求 （size 100）
          const paramsList = chunkArray(openIds)
          console.log(paramsList)
          for (let i = 0; i < paramsList.length; i++) {
            //获取openid 对应用的互信息 含 unionid
            const userBean : any = await getUsers(mpTokenBean.access_token, JSON.stringify({
              user_list: paramsList[i]
            }))
            //小程序的unionid 和 公众号的unionid 相同 取出目标用户
            const target = userBean.user_info_list.find((item : any) =>
              miniProgram.unionid == item.unionid
            )
            //得到公众号的openid 跳出循环
            if (target) {
              targetOpenId = target.openid
              break;
            }
          }
          uni.hideLoading()
          //绑定
          console.log(targetOpenId)
        }
      }
    });
  }
  function chunkArray(arr : any, chunkSize = 100) {
    const chunks = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
      chunks.push(arr.slice(i, i + chunkSize));
    }
    return chunks;
  }

  function subScrip() {
    const tmplIds = [
      'ovGbSUJY-ovjS8mwFiAhlSpA2S877ZyHgDy_G-U3MJI'
    ]
    uni.requestSubscribeMessage({
      tmplIds,
      success(res) {
        console.log('requestSubscribeMessage', res);
        uni.showToast({
          title: '订阅成功',
          icon: 'none',
          duration: 2000
        })
      },
      fail(err) {
        console.log('requestSubscribeMessage', err);
        uni.showToast({
          title: err.errMsg,
          icon: 'none',
          duration: 2000
        })
      },
      complete(info) {
        console.log('requestSubscribeMessage', info)
      }
    })
  }

  function forgetPassword() {
    uni.navigateTo({
      url: '/pages/login/forgetpassword',
    })
  }
  //复制设备号
  const copyDeviceNumber = () => {
    uni.setClipboardData({
      data: deviceNumber.value,
      success() {
        uni.showToast({
          title: "复制成功",
          icon: 'none'
        })
      }
    })
  }
  // 表单提交
  const onSubmit = async () => {

    if (Func.isEmpty(form.value.loginName)) {
      uni.showToast({
        title: '请输入账号',
        icon: 'none'
      })
      return
    }
    if (Func.isEmpty(form.value.passwd)) {
      uni.showToast({
        title: '请输入您的密码',
        icon: 'none'
      })
      return
    }
    loading.value = true
    try {
      const res : any = await postLoginAPI(form.value)
      console.log(res, '返回信息是？')

      if (res) {

        // 保存用户信息
        memberStore.setUserInfo(res)
        uni.setStorageSync('account', form.value.loginName)
        uni.setStorageSync('password', form.value.passwd)
        const check : any = await checkDevice({ account: res.userPhone })
        console.log(check)

        if (!check.list || check.list.length == 0) {
          uni.showModal({

            title: '设备管理',
            content: '当前设备未注册，是否立即注册？注册后与该账户绑定',
            confirmText: '提交',
            success: function (modelRes) {
              if (modelRes.confirm) {
                bindDevice(res.userPhone, '')
              }
            }
          })
          return
        }
        const data = check.list[0]
        if (data.dataState == 1) {
          if (deviceNumber.value != data.deviceNumber) {
            uni.showModal({

              title: '设备管理',
              content: '检测到当前您的设备号已发生变化，是否重新提交申请',
              confirmText: '提交',
              success: function (modelRes) {
                if (modelRes.confirm) {
                  bindDevice(res.userPhone, data.deviceId)
                }
              }
            })
            return
          }
          // 成功提示
          uni.showToast({ icon: 'none', title: '登录成功' })
          // 页面跳转
          uni.switchTab({ url: '/pages/index/index' })
        } else if (data.dataState == 2) {//申请已拒绝

          uni.showModal({
            title: '设备管理',
            content: '设备绑定申请已拒绝，是否再次提交',
            confirmText: '提交',
            success: function (modelRes) {
              if (modelRes.confirm) {
                bindDevice(res.userPhone, data.deviceId)
              }
            }
          })
        } else if (data.dataState == 3) {
          uni.showModal({
            title: '设备管理',
            content: '设备绑定已解除，是否再次提交',
            confirmText: '提交',
            success: function (modelRes) {
              if (modelRes.confirm) {
                bindDevice(res.userPhone, data.deviceId)
              }
            }
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: '设备绑定申请审核中...'
          })
        }

      }

    } finally {
      loading.value = false
    }
  }
  const bindDevice = (userPhone : string, deviceId : string) => {
    if (Func.isEmpty(deviceId)) {//
      uni.showLoading({
        title: ''
      })
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          console.log(loginRes.code);
          getOpenId(loginRes.code).then((res) => {
            console.log(res.dataObj)
            if (Func.isEmpty(res.dataObj)) {
              visible.value = true
              //请先关注公众号
              uni.showToast({
                title: '请先关注公众号,后再次提交设备申请',
                icon: 'none'
              })

              return
            }
            saveClDevice({
              account: userPhone,
              deviceType,
              deviceId,
              openid: res.dataObj,
              deviceNumber: deviceNumber.value
            }).then((device : any) => {
              console.log(device)
              if (device.success) {
                uni.showToast({
                  title: '设备绑定申请已提交,请耐心等待审核结果',
                  icon: 'none'
                })
              } else {
                uni.showToast({
                  title: '绑定设备失败',
                  icon: 'none'
                })
              }
            })

          })
        }
      })

      return
    }
    saveClDevice({
      account: userPhone,
      deviceType,
      deviceId,
      deviceNumber: deviceNumber.value
    }).then((device : any) => {
      console.log(device)
      if (device.success) {
        uni.showToast({
          title: '设备绑定申请已提交,请耐心等待审核结果',
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: '绑定设备失败',
          icon: 'none'
        })
      }
    })
  }

  //绑定回调
  const bindload = (detail : any) => {
    console.log('bindload', detail)
    uni.showToast({
      title: detail,
      icon: 'none'
    })
  }
  //绑定失败回调
  const binderror = (detail : any) => {
    console.log('bindload', detail)
    uni.showToast({
      title: detail,
      icon: 'none'
    })
  }
  //长按识别   二维码关注公众号
  const previewImage = (e : any) => {
    uni.previewImage({
      // 需要预览的图片链接列表。若无需预览，可以注释urls
      urls: [e.target.src],
      // 为当前显示图片的链接/索引值
      current: e.target.src,
      // 图片指示器样式
      indicator: 'default',
      // 是否可循环预览
      loop: false,
      // 长按图片显示操作菜单，如不填默认为保存相册
      // longPressActions:{
      // 	itemList:[this.l('发送给朋友'),this.l]
      // },
      success: res => {
        console.log('previewImage res', res);
        visible.value = false
      },
      fail: err => {
        console.log('previewImage err', err);
        visible.value = false
      }
    });
  }
</script>


<template>
  <view class="viewport">
    <image class="logo_img" src="../../static/index/icon_logo.png" />
    <!-- <official-account @load="bindload" @error="binderror"></official-account> -->
    <view class="login_container">
      <view class="input_container">
        <view class="title">账号</view>
        <input v-model="form.loginName" placeholder="请输入用户名/手机号码" type="tel" />
      </view>
      <view class="input_container">
        <view class="title">密码</view>

        <uni-easyinput v-model="form.passwd" :styles="styles" placeholderStyle="color: #999; font-size: 16px;"
          :inputBorder="false" type="password" placeholder="请输入密码" />
      </view>
      <view class="forget-container">
        <!-- <view class="forget-button" @click="forgetPassword">忘记密码?</view> -->
      </view>
      <view class="login-button">
        <nut-button size="large" class="button" type="primary" :loading="loading" :disabled="loading" @tap="onSubmit">
          登录
        </nut-button>
      </view>
      <view class="phone_number_container" @click="copyDeviceNumber">{{"设备号:"+deviceNumber}}
        <view class="copy">复制</view>
      </view>
    </view>
    <nut-popup v-model:visible="visible" position="bottom" z-index="999">
      <view class="region-header">
        <text class="region-title">关注公众号
        </text>
        <nut-icon name="close" @click="visible = false" />
      </view>
      <view class="region-content">
        <text class="title_bold">长按识别【二维码】立即关注</text>
        <image class="qrcode" :show-menu-by-longpress="true" src="../../static/qrcode.png" @longpress="previewImage">
        </image>

      </view>
    </nut-popup>
  </view>
</template>

<style lang="scss">
  page {
    --nut-button-large-font-size: 32rpx;
    --nut-primary-color: #54B9CC;
    --nut-button-large-height: 96rpx;
    --nut-button-large-line-height: 96rpx;
    --nut-button-border-radius: 48rpx;
    height: 100%;
  }

  .viewport {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .logo_img {
    margin-left: auto;
    margin-right: auto;
    margin-top: 332rpx;
    margin-bottom: 144rpx;
    width: 408rpx;
    height: 112rpx;
  }



  .input_container {
    background-color: rgba(179, 220, 246, 0.10);
    margin-left: 60rpx;
    margin-top: 48rpx;
    padding-right: 15rpx;
    margin-right: 60rpx;
    border-radius: 44rpx;
    align-items: center;
    display: flex;
    flex-direction: row;
  }

  .login_container {
    display: flex;
    flex-direction: column;
    background-color: white;

    .input {
      height: 80rpx;
      font-size: 28rpx;
    }

    .title {
      margin: 30rpx 36rpx;
      color: #222;
      font-size: 33rpx;
    }

    .button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 120rpx;
      marigin-top: 268rpx;
      font-size: 34upx;
      border-radius: 20rpx;
      font-size: 30rpx;
      background-color: #54B9CC;
      color: #fff;

      .icon {
        font-size: 40rpx;
        margin-right: 6rpx;
      }
    }

    .diviler {
      width: 100%;
      height: 2rpx;
      margin-top: 15rpx;
      background-color: #999;
    }

    .forget-container {
      width: 100%;
      margin-top: 20rpx;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
    }

    .phone_number_container {
      display: flex;
      flex-direction: row;
      text-align: center;
      margin-top: 240rpx;
      margin-left: auto;
      margin-right: auto;
      font-size: 26rpx;
      color: #C3C6CD;
    }

    .copy {
      color: #54B9CC;
      margin-left: 10rpx;
      font-size: 28rpx;
      font-weight: bold;
    }

    .forget-button {
      color: #C3C6CD;
      margin-right: 80rpx;
      padding: 15rpx 20rpx;
      background-color: transparent;
      font-size: 28rpx;
    }

    .login-button {
      margin-top: 100rpx;
      margin-left: 64rpx;
      margin-right: 64rpx;
    }

    .wechat {
      background-color: #06c05f;
    }

    .extra {
      flex: 1;
      padding: 70rpx 70rpx 0;

      .caption {
        width: 440rpx;
        line-height: 1;
        border-top: 1rpx solid #ddd;
        font-size: 26rpx;
        color: #999;
        position: relative;

        text {
          transform: translate(-40%);
          background-color: #fff;
          position: absolute;
          top: -12rpx;
          left: 50%;
        }
      }

      .options {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 70rpx;

        button {
          padding: 0;
          background-color: transparent;

          &::after {
            border: none;
          }
        }
      }

      .icon {
        font-size: 24rpx;
        color: #444;
        display: flex;
        flex-direction: column;
        align-items: center;

        &::before {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 80rpx;
          height: 80rpx;
          margin-bottom: 6rpx;
          font-size: 40rpx;
          border: 1rpx solid #444;
          border-radius: 50%;
        }
      }

      .icon-weixin::before {
        border-color: #06c05f;
        color: #06c05f;
      }
    }
  }

  @keyframes animate__shakeY {
    0% {
      transform: translate(0, 0);
    }

    50% {
      transform: translate(0, -5rpx);
    }

    100% {
      transform: translate(0, 0);
    }
  }

  .animate__shakeY {
    animation: animate__shakeY 0.2s ease-in-out 3;
  }

  .button-privacy-wrap {
    position: relative;

    .button-opacity {
      opacity: 0;
      position: absolute;
      z-index: 1;
    }
  }

  .tips {
    position: absolute;
    bottom: 80rpx;
    left: 20rpx;
    right: 20rpx;
    font-size: 22rpx;
    color: #999;
    text-align: center;

    .radio {
      transform: scale(0.6);
      margin-right: -4rpx;
      margin-top: -4rpx;
      vertical-align: middle;
    }

    .link {
      display: inline;
      color: #28bb9c;
    }
  }

  .qrcode {
    width: 40vw;
    margin-top: 60rpx;
    height: 40vw;
  }

  .region-content {
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    padding: 20rpx;
    margin-bottom: 140rpx;
    font-style: bold;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .region-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 30rpx 16rpx;
    font-size: 32rpx;
  }

  .region-task-title {
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    flex-grow: 1;
    font-size: 32rpx;
    dispaly: flex;
    flex-direction: row;
    align-items: center;

    &:before {
      content: "";
      margin-left: 15px;
      padding-left: 8px;
      border-left: 10rpx solid #54B9CC;
      height: 35rpx;
      display: inline-block;
      vertical-align: middle;
    }
  }

  .region-title {
    flex-grow: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
  }
</style>
